package net.cmkj.mine.core.admin.sys.dept;

import com.alibaba.fastjson.JSON;
import net.cmkj.mine.bean.CmkjTree;
import net.cmkj.mine.bean.SysDept;
import net.cmkj.mine.bean.SysUser;
import net.cmkj.mine.common.model.InvokeResult;
import net.cmkj.mine.common.model.ZtreeView;
import net.cmkj.mine.util.CommonUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DeptService {
	
	private static Logger log = LogManager.getLogger(DeptService.class);
	
	public static final DeptService service = new DeptService();
	private final SysDept dao = SysDept.dao;
	
	public Map<String, Object> getTreeGridView() throws Exception {
		log.info("获取部门树");
		return dao.getTreeGridView();
	}
	
	public List<ZtreeView> getZtreeViewList() throws Exception {
		log.info("获取选择部门树");
		return dao.getZtreeViewList();
	}
	
	public SysDept findById(Integer id) throws Exception {
		log.info("获取部门");
		return dao.findById(id);
	}
	
	public InvokeResult save(Integer id, String name, String seq, String des, Integer pId, SysUser user) throws Exception {
		log.info("部门保存");
		return dao.save(id, name, seq, des, pId,user);
	}
	
	public InvokeResult visible(Integer id, Integer visible) throws Exception {
		log.info("设置部门状态");
		return dao.setVisible(id, visible);
	}

	@SuppressWarnings("unchecked")
	public String getDepts() throws Exception {
		Map<String, Object> deptmap = dao.getTreeGridView();
		List<Map<String, Object>> maplist = (List<Map<String, Object>>) deptmap.get("data");
		List<CmkjTree> list = new ArrayList<CmkjTree>();
		CmkjTree tree;
		Map<String, String> attributes;
		for (Map<String,Object> map :maplist) {
			tree = new CmkjTree();
			tree.setId(CommonUtils.converString(map.get("id")));
			tree.setTitle(CommonUtils.converString(map.get("name")));
			if(!CommonUtils.converString(map.get("pId")).equals(""))
				tree.setFuid(CommonUtils.converString(map.get("pId")));
			attributes = new HashMap<String,String>();
			attributes.put("url", CommonUtils.converString(map.get("url")));
			tree.setAttributes(attributes);
            tree.setSpread(true);
			list.add(tree);
		}
		List<CmkjTree> rootlist = new ArrayList<CmkjTree>();
		for(int i=0;i<list.size();i++){
			tree = list.get(i);
			tree.setChildren(list);
            tree.setSpread(true);
			if(tree.getFuid() == null)
				rootlist.add(tree);
		}
		return JSON.toJSONString(rootlist).replace("\"checked\":\"\",", "");
	}

}
